package cloud.xlh.dynamic_env_refresh_server.controller;

import cloud.xlh.dynamic_env_refresh_server.service.LongPollingService;
import cloud.xlh.infrastructure.utils.FileUtil;
import cloud.xlh.infrastructure.utils.StringUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/3/10 11:36
 * @ Description:
 */
@Slf4j
@RestController
@RequestMapping("/v1/cs/configs")
public class ConfigController {

    @Autowired
    private LongPollingService longPollingService;
    /**
     * The client listens for configuration changes.
     */
    @PostMapping("/listener")
    //@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
    public void listener(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        ServletInputStream inputStream = request.getInputStream();

        String probeModify = request.getHeader("Listening-Configs");
        if (StringUtil.isEmpty(probeModify)) {
            log.warn("invalid probeModify is blank");
            throw new IllegalArgumentException("invalid probeModify");
        }

        //probeModify = URLDecoder.decode(probeModify, Constants.ENCODE);

        //Map<String, String> clientMd5Map;
        /*try {
            clientMd5Map = MD5Util.getClientMd5Map(probeModify);
        } catch (Throwable e) {
            throw new IllegalArgumentException("invalid probeModify");
        }*/

        // do long-polling
        //todo 将字符串形式的配置转化成map形式
        int lastIndexOf = probeModify.lastIndexOf(":");
        String key = probeModify.substring(0, lastIndexOf);
        String value = probeModify.substring(lastIndexOf + 1);
        Map<String, String> clientMd5Map = new HashMap<>();
        clientMd5Map.put(key , value);
        doPollingConfig(request, response, clientMd5Map, probeModify.length());
    }


    /**
     * long polling the config.
     */
    public String doPollingConfig(HttpServletRequest request, HttpServletResponse response,
                                  Map<String, String> clientMd5Map, int probeRequestSize) throws IOException {
            longPollingService.addLongPollingClient(request, response, clientMd5Map, probeRequestSize);
            return HttpServletResponse.SC_OK + "";
    }

    @Value("${remote.serviceCallListFile.location}")
    private String remoteServiceCallListFileLocation;

    @GetMapping("/getChangeConfig")
    public String getChangeConfig() {
        String changeConfig = FileUtil.readCommonFileAndToStr(FileUtil.PathTypeCode.ABSOLUTE_PATH.getCode(), remoteServiceCallListFileLocation);
        JSONObject changeConfigJsonObject = JSONObject.parseObject(changeConfig);
        String serviceListStr = (String) changeConfigJsonObject.get("svcCode");
        if (!StringUtil.isEmpty(serviceListStr)) {
            log.info("发生变化的配置->{}" , serviceListStr);
            return serviceListStr;
        }
        return "";
    }
}
